package dao;

import java.util.ArrayList;
import java.util.List;
import hbt.HibernateUtil;
import negocio.Mozo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class MozoDAO 
{
	private static MozoDAO instancia = null;
	private static SessionFactory sf = null;
	private Session session = null;
	
	public static MozoDAO getInstancia()
	{
		if(instancia == null)
		{
			sf = HibernateUtil.getSessionFactory();
			instancia = new MozoDAO();
		} 
		return instancia;
	}
	
	private Session getSession()
	{
		if(session == null || !session.isOpen())
			session = sf.openSession();
		return session;
	}
	
	public void closeSession()
	{
		if (session.isOpen()) session.close();
	}
	
	public void update(Object o)
	{
		Session s=getSession();
		s.beginTransaction();
		s.update(o);
		s.flush();
		s.getTransaction().commit();
		closeSession();
	}
	
	public Mozo getMozo(int dniMozo)
	{
		Session s=getSession();
		Mozo m = (Mozo) s.get(Mozo.class, new Integer(dniMozo));
		closeSession();
		return m;
	}


	public List<Mozo> getAllMozos() {
		Session s = getSession();
		s.beginTransaction();
		Mozo m = new Mozo();
		List<Mozo>lista= new ArrayList<>();
		for(Integer id : this.getAllid()){
			m.setId_dni(id);
			s.load(m, m.getId_dni());
			lista.add(m);
		}
		s.flush();
		s.getTransaction().commit();
		closeSession();
		return lista;
	}
	
	
	@SuppressWarnings("unchecked")
	private List<Integer> getAllid(){
		Session s = getSession();
		List<Integer>lista=s.createQuery("select m.id_mozo from Mozo m").list();
		return lista;
	}

	public void persistMozo(Mozo m) {
		Session s=getSession();
		s.beginTransaction();
		s.persist(m);
		s.flush();
		s.getTransaction().commit();
		closeSession();
	}

	public Mozo getMozoPorNumeroMesa(int numeroMesa) {
		Session s = getSession();
		Mozo mozo = (Mozo) s.createQuery("select m from Mozo m join m.sector.mesas me where me.numeroMesa = :numeroMesa")
				.setInteger("numeroMesa", numeroMesa).uniqueResult();
		closeSession();
		return mozo;
	}
	
	
	
}